/*
 * GraphML.java
 *
 * Created on September 14, 2006, 2:37 PM
 *
 * (C) 2006 R. Alexander Milowski
 */

package com.smallx.xproc.compiler.graph;

import java.net.URI;
import org.infoset.xml.Element;
import org.infoset.xml.InfosetFactory;
import org.infoset.xml.ItemConstructor;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.Name;
import org.infoset.xml.XMLException;

/**
 *
 * @author alex
 */
public class GraphML {

   static URI NAMESPACE = URI.create("http://graphml.graphdrawing.org/xmlns");
   static Name GRAPHML = Name.create("{http://graphml.graphdrawing.org/xmlns}graphml");
   static Name GRAPH = Name.create("{http://graphml.graphdrawing.org/xmlns}graph");
   static Name NODE = Name.create("{http://graphml.graphdrawing.org/xmlns}node");
   static Name EDGE = Name.create("{http://graphml.graphdrawing.org/xmlns}edge");
   
   ItemConstructor constructor;
   
   /** Creates a new instance of GraphML */
   public GraphML() {
      this(InfosetFactory.getDefaultInfoset().createItemConstructor());
   }
   
   public GraphML(ItemConstructor constructor) {
      this.constructor = constructor;
   }
   
   public void generate(Graph graph, ItemDestination output) 
      throws XMLException
   {
      output.send(constructor.createDocument());
      output.send(constructor.createElement(GRAPHML));
      Element g = constructor.createElement(GRAPH);
      g.setAttributeValue("id",graph.getId());
      g.setAttributeValue("edgedefault","directed");
      output.send(g);
      output.send(constructor.createCharacters("\n"));
      for (Vertex v : graph.getVertices()) {
         Element node = constructor.createElement(NODE);
         node.setAttributeValue("id",v.getId());
         node.setAttributeValue("label",v.getLabel());
         output.send(node);
         output.send(constructor.createElementEnd(NODE));
         output.send(constructor.createCharacters("\n"));
      }
      for (Edge e : graph) {
         Element edge = constructor.createElement(EDGE);
         edge.setAttributeValue("label",e.getLabel());
         edge.setAttributeValue("source",e.getSource().getId());
         edge.setAttributeValue("target",e.getTarget().getId());
         if (e.isDirected()) {
            edge.setAttributeValue("directed","true");
         }
         output.send(edge);
         output.send(constructor.createElementEnd(EDGE));
         output.send(constructor.createCharacters("\n"));
      }
      output.send(constructor.createElementEnd(GRAPH));
      output.send(constructor.createElementEnd(GRAPHML));
      output.send(constructor.createDocumentEnd());
   }
   
}
